package com.spm.librarianmanagersystem.service.impl;

import com.spm.librarianmanagersystem.mapper.FineMapper;
import com.spm.librarianmanagersystem.mapper.MemberMapper;
import com.spm.librarianmanagersystem.mapper.ReturnMapper;
import com.spm.librarianmanagersystem.pojo.Borrow;
import com.spm.librarianmanagersystem.service.ReturnService;
import org.apache.ibatis.transaction.TransactionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.InvalidParameterException;
import java.util.Date;

@Service("ReturnService")
@Transactional
public class ReturnServiceImpl implements ReturnService {
    @Autowired
    ReturnMapper returnMapper;

    @Autowired
    FineMapper fineMapper;

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    private SendEmailImpl sei;

    @Override
    @Transactional
    public String returnBook(String currentUserId, Integer borrowNum) throws Exception {
        Borrow borrow = returnMapper.getBorrowRecord(borrowNum, currentUserId);

        // 验证是否有对应的借书记录
        if (borrow == null) {
            throw new InvalidParameterException("未找到借阅记录");
        }

        // 验证是否逾期
        Date now = new Date(System.currentTimeMillis());
//        if (borrow.getDueTime().before(now)) {
//            throw new TransactionException("已超过归还日期");
//        }

        // 验证是否支付罚款
//        Double fine = fineMapper.getFineByBorrowNum(borrowNum);
//        if (fine == null) {
//            throw new TransactionException("未支付罚款");
//        }

        // 归还图书
        Boolean ok = returnMapper.updateBorrowForReturn(borrowNum, now);
        if (ok == null || !ok) {
            throw new TransactionException("更新借书记录失败");
        }
        ok = returnMapper.updateBookForReturn(borrow.getBookId(), borrow.getISBN());
        if (ok == null || !ok) {
            throw new TransactionException("更新图书记录失败");
        }

        sei.sendEmailReservRemind(borrow.getISBN());
        return "操作成功!";
    }
}
